<?php

namespace App;

use Zizaco\Entrust\EntrustRole;
use DB;

class Role extends EntrustRole
{

    public $timestamps = false;
    protected $table = 'roles';

    /**
     * 添加角色
     * @return array
     */
    public static function AddRole()
    {
        $return = ['status' => 2, 'message' => '创建失败'];

        $role = new Role();
        $role->name = request('name');
        $role->display_name = request('display_name');
        $role->description = request('description');
        $role->created_at = $role->updated_at = time();
        if ($role->save()) {
            $return = ['status' => 1, 'message' => '创建成功'];
        }

        return $return;
    }

    // 修改角色
    public static function ModifyRole($role_id)
    {
        $return = ['status' => 2, 'message' => '修改失败'];

        $role = Role::findOrFail($role_id);
        $role->name = request('name');
        $role->display_name = request('display_name');
        $role->description = request('description');
        $role->updated_at = time();
        if ($role->save()) {
            $return = ['status' => 1, 'message' => '修改成功'];
        }
        // 权限操作
        DB::table('permission_role')->where('role_id', $role_id)->delete();
        if ($permissions = request('permissions', null)) {
                $role->perms()->sync($permissions);
        };

        return $return;
    }

    // 获取角色权限
    public static function Permissions($role_id)
    {
        $return = [];
        $datas = DB::table('permission_role')->where('role_id', $role_id)->get();
        if ($datas) {
            foreach ($datas as $data) {
                $permission = Permission::findOrFail($data->permission_id);
                $return[] = $permission;
            }
        }
        return $return;
    }
}